frappe.ui.form.on('Job Card', {

    refresh: function(frm) {
        // 首工序尚无追踪号时，允许生成追踪号
        // if (frm.doc.docstatus === 0 && frm.doc.work_order){
        //     frappe.call({
        //         method: "light_mes.api.is_work_order_first_operation",                
        //         args: {
        //             work_order: frm.doc.work_order,
        //             operation_id: frm.doc.operation_id
        //         },
        //         callback: function(r){
        //             if (r.message){
        //                 frm.add_custom_button(__('Tracking Numbers'), function() {
        //                     create_tracking_numbers(frm);
        //                 }, __('Create'));
        //             }
        //         }
        //     });
        // }

        // 允许在制品入库的情况 - 需要已提交状态
        if (frm.doc.docstatus === 1 && frm.doc.custom_enable_wip_receipt && frm.doc.custom_wip_qty < frm.doc.for_quantity) {
            // 检查是否已经有在制品入库记录 - 使用link_doctype查询子表字段
            frappe.call({
                method: "frappe.client.get_list",
                args: {
                    doctype: "Wip Transfer",
                    fields: ["name"],
                    filters: [
                        ["Wip Transfer Item", "job_card", "=", frm.doc.name],
                        ["Wip Transfer", "docstatus", "=", 1],
                        ["Wip Transfer", "type", "=", "Receive from Workshop"]
                    ]
                },
                callback: function(r) {
                    // 如果没有相关记录或记录数量不足，显示下推按钮
                    let can_create = true;
                    if (r.message && r.message.length > 0) {
                        // 可以进一步检查已入库数量是否小于加工单数量
                        // 这里简化处理，如果有记录且加工单完成数量已达到总数量，就不显示按钮
                        if (frm.doc.completed_qty >= frm.doc.for_quantity) {
                            can_create = false;
                        }
                    }
                    
                    if (can_create) {
                        frm.add_custom_button(__('Receive from Workshop'), function() {
                            create_wip_transfer(frm, "Receive from Workshop");
                        }, __('Create'));
                    }
                }
            });
        }
        
        // 允许委外的情况 - 草稿状态即可
        if (frm.doc.docstatus === 0 && frm.doc.custom_is_subcontracting === 1) {
            // 首先获取工单工序的发料和入库数量
            frappe.call({
                method: "frappe.client.get",
                args: {
                    doctype: "Work Order Operation",
                    parent: "Work Order",
                    name: frm.doc.operation_id
                },
                callback: function(r) {
                    if (r.message) {
                        let operation = r.message;
                        let sent_qty = operation.custom_sent_qty || 0;
                        let received_qty = operation.custom_received_qty || 0;
                        
                        // 同时查询委外发料单和委外入库单
                        frappe.call({
                            method: "frappe.client.get_list",
                            args: {
                                doctype: "Wip Transfer",
                                fields: ["name", "type"],
                                filters: [
                                    ["Wip Transfer Item", "job_card", "=", frm.doc.name],
                                    ["Wip Transfer", "type", "in", ["Send to Supplier", "Receive from Supplier"]]
                                ]
                            },
                            callback: function(r) {
                                let has_send_to_supplier = false;
                                let has_receive_from_supplier = false;
                                
                                // 检查是否已有委外发料单和委外入库单
                                if (r.message && r.message.length > 0) {
                                    r.message.forEach(function(doc) {
                                        if (doc.type === "Send to Supplier") {
                                            has_send_to_supplier = true;
                                        } else if (doc.type === "Receive from Supplier") {
                                            has_receive_from_supplier = true;
                                        }
                                    });
                                }
                                
                                // 如果没有委外发料单，显示委外发料按钮
                                if (!has_send_to_supplier) {
                                    frm.add_custom_button(__('Send to Supplier'), function() {
                                        create_wip_transfer(frm, "Send to Supplier");
                                    }, __('Create'));
                                }
                                
                                // 只有在满足以下条件时才显示委外入库按钮：
                                // 1. 没有已存在的委外入库单
                                // 2. 有发料数量且发料数量 > 入库数量
                                if (!has_receive_from_supplier && sent_qty > 0 && sent_qty > received_qty) {
                                    frm.add_custom_button(__('Subcontracting Receipt'), function() {
                                        create_wip_transfer(frm, "Receive from Supplier");
                                    }, __('Create'));
                                }
                            }
                        });
                    }
                }
            });
        }

        // Add update price button
        frm.add_custom_button(__('Update Price'), function() {
            frm.call({
                doc: frm.doc,
                method: 'update_operation_price',
                args: {
                    force_save: 1
                },
                freeze: true,
                freeze_message: __('Updating price...'),
                callback: function(r) {
                    frm.reload_doc();
                    frappe.show_alert(__("Updated Job Card Service Price OK"));
                }
            });
        }, __('Actions'));
    },
    generate_tracking_numbers: function(frm, qty){
        frappe.call({
            method: "light_mes.api.generate_tracking_numbers",
            args: {
                work_order: frm.doc.work_order,
                count: qty
            },
            callback: function (r) {
                tracking_number_list = r.message;
                if (tracking_number_list && tracking_number_list.length) {
                    for (let tracking_number of tracking_number_list) {
                        let child = frm.add_child("tracking_details");
                        child.tracking_number = tracking_number;
                    }
                    refresh_field("tracking_details");
                }
            },
        });
    }
});

// 创建在制品移转单的函数
function create_wip_transfer(frm, transfer_type) {
    frappe.model.open_mapped_doc({
        method: "light_mes.light_mes.overrides.job_card.make_wip_transfer",
        frm: frm,
        args: {
            transfer_type: transfer_type
        }
    });
}

function create_tracking_numbers(frm){
    frappe.prompt(
        {
            fieldtype: "Int",
            label: __("Quantity"),
            fieldname: "qty",
            default: frm.doc.for_quantity,
        },
        (data) => {
            frm.events.generate_tracking_numbers(frm, data.qty);
        },
        __("Enter Value")
    );
}